<!-- 
//  author 白珅瑞
//  contcat 15903482433
 -->

<template>
    <div>
        <!-- 查询条件框 -->
        <el-form :inline="true" :model="queryForm" label-width="100px">
            <el-form-item label="物料名称" prop="name">
                <el-input v-model="queryForm.name" placeholder="请输入物料名称"></el-input>
            </el-form-item>
            <el-form-item label="物料描述" prop="description">
                <el-input v-model="queryForm.description" placeholder="请输入物料描述"></el-input>
            </el-form-item>
        </el-form>
        <!-- 头部操作按钮 -->
        <el-header style="background-color: #fff; padding: 10px;display: flex;">
            <el-button @click="openCreateDialog">添加物料</el-button>
            <!-- 导入物料按钮 -->
            <el-upload action="/api/materials/import" :on-success="handleImportSuccess" :on-error="handleImportError"
                :before-upload="beforeUpload" accept=".xls,.xlsx" :show-file-list="false">
                <el-button type="primary" style="margin-left: 10px;">导入物料</el-button>
            </el-upload>
            <el-button type="primary" @click="exportMaterials" style="margin-left: 10px;">导出物料</el-button>
            <el-button @click="this.fetchMaterials(currentPage, pageSize)" style="margin-left: 10px;">查询</el-button>
            <el-button @click="resetQueryForm" style="margin-left: 10px;">重置</el-button>

        </el-header>

        <!-- 物料列表表格 -->
        <el-table :data="materials" style="width: 100%">
            <el-table-column prop="name" label="物料名称"></el-table-column>
            <el-table-column prop="quantity" label="物料数量"></el-table-column>
            <el-table-column prop="description" label="物料描述"></el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-button @click="openEditDialog(scope.row)" size="small">编辑</el-button>
                    <el-popconfirm title="确定删除吗？" confirm-button-text='确定' cancel-button-text='取消'
                        @confirm="deleteMaterial(scope.row.id, scope.row.version)">
                        <template #reference>
                            <el-button type="danger" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>

                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <view class="paginationStyle">
            <el-pagination background layout="prev, pager, next" :total="totalItems" @current-change="handlePageChange">
            </el-pagination>
        </view>

        <!-- 新建物料弹窗 -->
        <el-dialog :title="editMaterialId ? '编辑物料' : '添加物料'" v-model="dialogVisible" @close="resetForm">
            <el-form :model="form" label-width="100px">
                <el-form-item label="物料名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入物料名称"></el-input>
                </el-form-item>
                <el-form-item label="物料数量" prop="quantity">
                    <el-input-number v-model="form.quantity" placeholder="请输入物料数量"></el-input-number>
                </el-form-item>
                <el-form-item label="物料描述" prop="description">
                    <el-input v-model="form.description" placeholder="请输入物料描述"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { getMaterials, createMaterial, updateMaterial, deleteMaterial, exportMaterials } from '@/api/material'

export default {
    data() {
        return {
            materials: [],       // 物料列表数据
            currentPage: 1,      // 当前页码
            pageSize: 10,        // 每页显示的数量
            totalItems: 0,       // 总物料数
            form: {
                name: '',
                quantity: '',
                description: '',
            },
            queryForm: {
                name: '',
                description: '', 
            },
            dialogVisible: false,  // 新建/编辑 弹出弹出框
            editMaterialId: null,  // 当前行物料id
            version: null, // 当前行物料版本
        };
    },
    methods: {
        // 获取物料列表
        async fetchMaterials(page = this.currentPage, size = this.pageSize) {            
            try {   
                const obj = {
                    page: page,
                    size: size,
                    ...this.queryForm
                }             
                const response = await getMaterials(obj);                
                this.materials = response.data.list;
                this.totalItems = response.data.total;
            } catch (error) {
                this.$message.error('加载物料失败');
            }
        },

        // 打开新建物料弹窗
        openCreateDialog() {            
            this.dialogVisible = true;
        },

        // 打开编辑物料弹窗
        openEditDialog(material) {
            this.editMaterialId = material.id;
            this.version = material.version;
            this.form.name = material.name;
            this.form.quantity = material.quantity;
            this.form.description = material.description;
            this.dialogVisible = true;
        },

        // 提交新建物料表单
        async submitForm() {
            try {
                if (this.editMaterialId) {
                    await updateMaterial({ version: this.version, id: this.editMaterialId, ...this.form });
                    this.$message.success('物料更新成功');
                } else {
                    await createMaterial(this.form);
                    this.$message.success('物料添加成功');
                }         
                this.dialogVisible = false;
                this.fetchMaterials();
            } catch (error) {
                this.$message.error('失败');
            }
        },

        // 删除物料
        async deleteMaterial(id, version) {
            try {
                await deleteMaterial(id, version);
                this.$message.success('物料删除成功');
                this.fetchMaterials();
            } catch (error) {
                this.$message.error('删除失败');
            }
        },

        // 重置表单
        resetForm() {
            this.form.name = '';
            this.form.quantity = '';
            this.form.description = '';
            this.editMaterialId = '';
        },

        resetQueryForm() {
            this.queryForm = {
                name: '',
                description: '', 
            }
        },

        // 导出物料
        async exportMaterials() {
            try {
                // 生成时间戳
                const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, '');
                const response = await exportMaterials(this.queryForm);
                const blob = response.data;
                const link = document.createElement('a');           
                link.href = URL.createObjectURL(blob);  // 创建一个对象URL
                link.download = `material_${timestamp}.xlsx`;  // 设置文件名
                link.click();  // 自动点击下载链接
                URL.revokeObjectURL(link.href);  // 释放对象URL
            } catch (error) {
                this.$message.error('导出失败');
            }
        },

        // 切换物料分页
        handlePageChange(page) {            
            this.currentPage = page;
            this.fetchMaterials(page);
        },

        // 导入成功后的回调
        handleImportSuccess() {
            this.$message.success('导入成功');
            this.fetchMaterials();  // 刷新物料列表
        },

        // 导入失败后的回调
        handleImportError() {
            this.$message.error('导入失败');
        },

        // 上传文件之前的校验
        beforeUpload(file) {
            const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            if (!isExcel) {
                this.$message.error('只能上传 Excel 文件');
            }
            return isExcel;
        }
    },
    created() {
        this.fetchMaterials();
    },
};
</script>

<style scoped>
/* 可以根据需求添加样式 */
.paginationStyle{
    float: right;
    margin-top: 20px;
}
</style>
